﻿using Esint.Common;
using Esint.JudicialAuction.Model.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using WebJudicialAuction.admin.bases;
using System.IO;

namespace WebJudicialAuction.admin.handler
{
    /// <summary>
    /// uploadFile 的摘要说明
    /// </summary>
    public class uploadFile : BaseHandler
    {
        
        protected override AjaxResult BusinessHandleFunc(string req_type, Dictionary<string, string> dicData)
        {
            Thread.Sleep(1500);

            AjaxResult ajaxResult = new AjaxResult();

            HttpPostedFile uploadFile = OwnContext.Request.Files["file"];

            if (uploadFile == null)
            {
                throw new ImportException("调用失败");
            }

            List<string> AllowTypes = CommonExtend.GetAppSetting("UploadAllowExt").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var fileExt = GetExtPart(uploadFile.FileName);
            if (AllowTypes.Contains(fileExt))
            {
                string fileSaveDir = OwnContext.Server.MapPath(CommonExtend.GetAppSetting("UploadPath"));

                if (!Directory.Exists(fileSaveDir))
                {
                    Directory.CreateDirectory(fileSaveDir);
                }

                string fileSaveName = $"{Guid.NewGuid().ToString()}{ fileExt }";

                uploadFile.SaveAs(fileSaveDir + fileSaveName);

                ajaxResult.flag = AjaxResultFlag.Success;
                ajaxResult.data = new { fileName = fileSaveName };
                ajaxResult.msg = AjaxMessage.OperationSuccess;
            }
            else
            {
                throw new ImportException("不允许上传该类型文件");
            }

            return ajaxResult;
        }

        private string GetSaveName(string fname)
        {
            int i1 = fname.LastIndexOf('.');
            //string frontpart = fname.Substring(0, i1);
            string expart = fname.Substring(i1);
            return Guid.NewGuid().ToString() + expart;
        }

        private string GetExtPart(string fname)
        {
            int i1 = fname.LastIndexOf('.');
            //string frontpart = fname.Substring(0, i1);
            string expart = fname.Substring(i1);
            return expart;
        }
    }
}